﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using log4net;
using Matrix.Common.Utility;
using Matrix.Common.Utility.Files;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.WxInterfaceFunc;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.MatrixCloudApi;
using ThoughtWorks.QRCode.Codec;

namespace Matrix.MaKaYunShang.McMagWeb.Controllers
{
    public  class BaseController : Controller
    {
        public readonly ILog Logger = LogManager.GetLogger(typeof(BaseController));
        public static string MkysMcMagMcId = ConfigurationManager.AppSettings["MkysMcMagMcId"];
        public MatrixCloudCenterInterFuncBll MatrixCloudCenterInterFuncBllobj = new MatrixCloudCenterInterFuncBll();

        /// <summary>
        /// 当前登录用户信息
        /// </summary>
        public McAccountDto CurrentUser;
        public List<McModules> McModules;
        public  BaseController()
        {
            CurrentUser = System.Web.HttpContext.Current.Session["McAccounts"] as McAccountDto;
            if (CurrentUser == null && System.Web.HttpContext.Current.Request.Cookies["McAccounts"] != null)
            {
                var username = System.Web.HttpContext.Current.Request.Cookies["McAccounts"].Values["u"];
                var password = System.Web.HttpContext.Current.Request.Cookies["McAccounts"].Values["p"];
                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    username = EncryptionLib.Decrypt(username, Encoding.UTF8);
                    var model = McAccountsBLL.Instance.GetModelByLogin(username, password);
                    if (model != null)
                    {
                        System.Web.HttpContext.Current.Session["McAccounts"] = model;
                        CurrentUser = model;
                        ViewBag.CurrentUser = CurrentUser;
                        ViewBag.HtmlNavMenu = ReadAndInsertNavMenuHtml(CurrentUser);
                    }
                    else
                    {
                        var newcookie = new HttpCookie("McAccounts") {Expires = DateTime.Now.AddDays(-1)};
                        System.Web.HttpContext.Current.Response.Cookies.Add(newcookie);
                    }
                }
                else
                {
                    var newcookie = new HttpCookie("McAccounts") {Expires = DateTime.Now.AddDays(-1)};
                    System.Web.HttpContext.Current.Response.Cookies.Add(newcookie);
                }
            }
            else if (CurrentUser != null)
            {
                ViewBag.CurrentUser = CurrentUser;
                ViewBag.HtmlNavMenu = ReadAndInsertNavMenuHtml(CurrentUser);
                McModules = System.Web.HttpContext.Current.Session["userModules" + CurrentUser.AccountId] as List<McModules>;
                if (McModules == null || McModules.Count()==0)
                {
                    var allowedModules = GetMcModules(CurrentUser);
                    allowedModules.RemoveAll(s => s == null);
                    System.Web.HttpContext.Current.Session["userModules" + CurrentUser.AccountId] = allowedModules;
                }
            }

        }
        /// <summary>
        ///     获取当前用户所有有权限执行的动作
        /// </summary>
        /// <returns></returns>
        private List<McModules> GetMcModules(McAccountDto accountInfo)
        {
            var lsModuleIds = McRoleModulePermissionBLL.Instance.GetModelListByRoleIdAndShopId(accountInfo.ShopId, accountInfo.RoleId).Select(x => x.ModuleId).ToList();
            return lsModuleIds.Select(moduleId => McModulesBLL.Instance.GetModel(moduleId)).ToList();
        }
        #region 生成二维码
// ReSharper disable once InconsistentNaming
        public ActionResult GenerateQRCode(string content)
        {
            try
            {
                if (null != content)
                {
                    //初始化二维码生成工具
                    var qrCodeEncoder = new QRCodeEncoder
                    {
                        QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE,
                        QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M,
                        QRCodeVersion = 0,
                        QRCodeScale = 8
                    };
                    //将字符串生成二维码图片
                    var image = qrCodeEncoder.Encode(content);
                    var ms = new MemoryStream();
                    image.Save(ms, ImageFormat.Png);
                    Response.BinaryWrite(ms.GetBuffer());
                    Response.End();

                }
            }
            catch (Exception ex)
            {
                Logger.Error("CloudCardController|GenerateQRCode|生成二维码出现异常,异常信息：" + ex.Message);
            }
            return View();
        }
        #endregion

        /// <summary>
        /// 从用户浏览器缓存中读取菜单，减少服务器压力，降低数据库IO
        /// </summary>
        /// <param name="currentAccount"></param>
        /// <returns></returns>
        private string ReadAndInsertNavMenuHtml(McAccountDto currentAccount)
        {
            string userNavMenu;
            var menuCookie = System.Web.HttpContext.Current.Request.Cookies["UserNavMenuCookie"];
            if (menuCookie != null)
            {
                userNavMenu = HttpUtility.UrlDecode(menuCookie.Values["strMenu"], Encoding.GetEncoding("UTF-8"));
                if (!string.IsNullOrEmpty(userNavMenu)) return userNavMenu;

                var strMenu = HttpUtility.UrlEncode(RenderNavigationMenu(currentAccount), Encoding.GetEncoding("UTF-8"));
                menuCookie.Values["strMenu"] = strMenu;
                userNavMenu = HttpUtility.UrlDecode(strMenu, Encoding.GetEncoding("UTF-8"));
            }
            else
            {
                var dt = DateTime.Now;
                var ts = new TimeSpan(1, 0, 0, 0, 0);
                var newMenuCookie = new HttpCookie("UserNavMenuCookie") { Expires = dt.Add(ts) };

// ReSharper disable once SpecifyACultureInStringConversionExplicitly
                newMenuCookie.Values["accountId"] = currentAccount.AccountId.ToString();
                newMenuCookie.Values["strMenu"] = HttpUtility.UrlEncode(RenderNavigationMenu(currentAccount), Encoding.GetEncoding("UTF-8"));
                System.Web.HttpContext.Current.Response.Cookies.Add(newMenuCookie);

                userNavMenu = HttpUtility.UrlDecode(newMenuCookie.Values["strMenu"], Encoding.GetEncoding("UTF-8"));
            }

            return userNavMenu;
        }

        /// <summary>
        /// 根据权限渲染导航栏
        /// </summary>
        /// <param name="currentAccount"></param>
        /// <returns></returns>
        private string RenderNavigationMenu(McAccountDto currentAccount)
        {
            var strHtmlNav = string.Empty;
            
            if (currentAccount == null) return strHtmlNav;

            // 获取当前用户的能访问的所有模块ID
            var lsModuleIds = McRoleModulePermissionBLL.Instance.GetModelListByRoleIdAndShopId(currentAccount.ShopId, currentAccount.RoleId).Select(x => x.ModuleId).ToList();

            // 店铺管理员可见所有模块，否则根据用户拥有的模块ID查找出模块
            List<McModules> lsModules = currentAccount.RoleId == 1 ? McModulesBLL.Instance.GetModuleList() : lsModuleIds.Select(moduleId => McModulesBLL.Instance.GetModel(moduleId)).ToList();
            
            // 根据模块查找出模块主类ID
            var lsModuleCateIds = lsModules.Select(x => x.ModuleCate).Distinct().ToList();
            foreach (var moduleCateId in lsModuleCateIds)
            {
                // 遍历主类找出组Html
                var htmlSubMenu = string.Empty;
                var moduleCate = McModuleCateBLL.Instance.GetModel(moduleCateId);
                strHtmlNav += moduleCate.HtmlText;
                var cateId = moduleCateId;
                var modules = lsModules.Where(x => x.ModuleCate == cateId).Select(x => x.HtmlText);
                // 遍历子类模块并找出Html替换主类的{subMenu} 完成菜单组装
                htmlSubMenu = modules.Aggregate(htmlSubMenu, (current, module) => current + module);
                strHtmlNav = strHtmlNav.Replace("{subMenu}", htmlSubMenu);
            }

            Logger.Info("BaseController | RenderNavigationMenu | " + strHtmlNav + " | currentAccount: " + currentAccount.UserName);
            return strHtmlNav;
        }

        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public string GetIp()
        {
            string result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(result))
                result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
                result = System.Web.HttpContext.Current.Request.UserHostAddress;
            if (string.IsNullOrEmpty(result) || !IsIp(result))
                return "127.0.0.1";
            return result;
        }

        /// <summary>
        /// 是否为ip
        /// </summary>
        public bool IsIp(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
        
        /// <summary>
        /// 获取加密或解密字符串
        /// </summary>
        /// <param name="type">1：加密、2：解密</param>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetEnDeCode(string type, string content)
        {
            var result = new { obj = "" };

            try
            {
                if (type == "1")
                {
                    result = new { obj = EncryptionLib.Encrypt(content, Encoding.UTF8) };
                }
                else if (type == "2")
                {
                    result = new { obj = EncryptionLib.Decrypt(content, Encoding.UTF8) };
                }
            }
            catch (Exception ex)
            {
                Logger.Info("BaseController | GetEnDeCode | " + ex.Message);
            }
            return Json(result);
        }

        /// <summary>
        /// 获取配置文件appSettings值
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetAppSetValue()
        {
            string keyName = Request["keyName"];
            string keyValue = ConfigLib.GetAppSettings(keyName);
            var resultJson = new JsonModel.ExecResultSimple
            {
                result = true,
                msg = keyValue
            };

            return Json(resultJson);
        }

        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="filterContext">异常上下文</param>
        /// <returns>异常提示信息</returns>
        protected override void OnException(ExceptionContext filterContext)
        {
            var exceptionResult = new Result
            {
                Status = false,
                Message = "系统错误，请重试！"
            };
            Logger.Error("系统未捕获异常:" + filterContext.Exception);
            if (ConfigurationManager.AppSettings["IsShowError"] == "false")
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = Json(exceptionResult, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    filterContext.Result = RedirectToAction("Error500", "Error");
                }
                filterContext.ExceptionHandled = true;
            }
        }

        /// <summary>
        /// 上传单张图片
        /// </summary>
        /// <param name="strFileRequest">Request.File[strFileRequest], 请求文件的名称</param>
        /// <param name="storeToPath">图片存储地址（相对路径，该图片对应的文件夹地址）</param>
        /// <param name="setWidth"></param>
        /// <param name="setHeight"></param>
        /// <returns></returns>
        public string UploadImage(string strFileRequest, string storeToPath, int setWidth, int setHeight)
        {
            var imageHelper = new ImagesFile();
            var file = Request.Files[strFileRequest];
            if (file == null || file.FileName.Length <= 0) return "";

            var uploadPath = ConfigurationManager.AppSettings["ImgFileUploadPath"] + "TempImg" + storeToPath;
            var extensionStr = file.FileName.Substring(file.FileName.LastIndexOf(".", StringComparison.Ordinal));
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + extensionStr;

            if (!Directory.Exists(uploadPath)) Directory.CreateDirectory(uploadPath);

            uploadPath += fileName;
            file.SaveAs(uploadPath);

            var dt = DateTime.Now;
            var newPathStr = ConfigurationManager.AppSettings["ImgFileUploadPath"];
            var tempPath = storeToPath + dt.Year + "/" + dt.Month + "/" + dt.Day + "/";
            newPathStr += tempPath;

            imageHelper.CreateDirectoryOrExist(newPathStr);
            imageHelper.CutPic(uploadPath, newPathStr + fileName, setWidth, setHeight);
            imageHelper.DeleteFileZhi(uploadPath);

            return tempPath + fileName;
        }


        /// <summary>
        /// 去单引号
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        protected string SqlSafe(string value)
        {
            return value.Replace("'", "''");
        }

        /// <summary>
        /// 获取当前接口当前云迈云项目资料
        /// </summary>
        /// <param name="pjMcId"></param>
        /// <returns></returns>
        protected MatrixCloudProjectInfo GetCurrentMatrixCloudProjectInfo(string pjMcId)
        {
            var localProjectInfo = MatrixCloudProjectInfoBLL.Instance.GetModelByPjMcId(pjMcId);
            if (localProjectInfo == null || localProjectInfo.Id == 0 ||
                string.IsNullOrWhiteSpace(localProjectInfo.PjMcId))
            {
                return null;
            }

            var checkResult =
                MatrixCloudCenterInterFuncBllobj.CheckAndGetMatrixCloudProjectInfo(localProjectInfo.PjCode);
            return checkResult.Status ? checkResult.Data : null;
        }

        protected MxApiWechatInfo GetWechatInfoByProjectInfo(string pjMcId, string pjSecret)
        {
            var resultWechatInfo = MatrixCloudCenterInterFuncBllobj.GetWechatInfo(pjMcId, pjSecret);
            return resultWechatInfo.Status ? resultWechatInfo.Data : null;
        }

        /// <summary>
        /// 获取公众号信息
        /// </summary>
        /// <param name="projectInfo"></param>
        /// <returns></returns>
        protected MxApiWechatInfo GetWeChatInfoByMcId(MatrixCloudProjectInfo projectInfo)
        {
            var resultWechatInfo = MatrixCloudCenterInterFuncBllobj.GetWechatInfo(projectInfo.PjMcId,
                projectInfo.PjSecret);

            if (!resultWechatInfo.Status || resultWechatInfo.Data == null ||
                string.IsNullOrEmpty(resultWechatInfo.Data.AppId) ||
                string.IsNullOrWhiteSpace(resultWechatInfo.Data.Secret))
            {
                Logger.Error(
                    "BaseController | GetWeChatInfoByMcId | Cannot get WechatMp Info from Matrix-Cloud-Center - " +
                    projectInfo.PjMcId);
                throw new Exception("Cannot get the WeChat info of the project McId - " + projectInfo.PjMcId);
            }
            return resultWechatInfo.Data;
        }

    }
}
